package com.atguigu.web;

import com.atguigu.dao.BookDao;
import com.atguigu.pojo.Book;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.CartItem;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;
import sun.nio.cs.ext.MS874;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YAO
 * @create 2021-05-11 20:40
 */
@WebServlet(name = "CartServlet", value = "/cartServlet")
public class CartServlet extends BaseServlet{

    private BookService bookService = new BookServiceImpl();

    /**
     * 加入购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数 商品编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        // 调用BookService.queryBookById(id)：Book 得到图书的信息
        Book book = bookService.queryBookById(id);
        // 把图书信息转化成为CartItem商品项
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
        // 调用cart.addItem(CartItem);添加商品项
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.addItem(cartItem);

        System.out.println(cart);
        // 将商品名保存到session域中
        req.getSession().setAttribute("lastAddItem",cartItem.getName());
        // 重定向回原来商品所在的页面
        resp.sendRedirect(req.getHeader("Referer"));

    }

    /**
     * 删除商品项
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取商品id
        String id = req.getParameter("id");
        //获取session域中的购物车属性
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart != null){
            //调用cart的deleteItem方法来删除商品
            cart.deleteItem(WebUtils.parseInt(id,0));
            //重定向回购物车页面
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }

    /**
     * 清空购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取购物车属性
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart != null){
            //调用cart.clear方法清空
            cart.clear();
            //跳转至购物车页面
            //req.getHeader("Referer")获取请求发送过来的地址
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }

    /**
     * 修改商品数量
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求的参数 商品编号，商品数量
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        int count = WebUtils.parseInt(req.getParameter("count"), 1);
        //获取库存
        Book book = bookService.queryBookById(id);
        int stock = book.getStock();
        if(stock < count){
            req.getSession().setAttribute("msg","您修改的商品数量必须小于库存数量");
            //重定向到购物车页面
            resp.sendRedirect(req.getHeader("Referer"));
            return;
        }
        //获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart != null){
            //更新商品数量
            cart.updateCount(id,count);
            req.getSession().setAttribute("msg","修改成功");
            //重定向到购物车页面
            resp.sendRedirect(req.getHeader("Referer"));
        }

    }

    protected void ajaxAddItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应体类型
        resp.setContentType("text/html; charset=UTF-8");
        // 获取请求的参数 商品编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        // 如果id为null
        if(id == 0){
            Map<String, Object> resultMap = WebUtils.ToResultMap(new HashMap<>(), "请求参数错误", 400);
        }
        // 调用BookService.queryBookById(id)：Book 得到图书的信息
        Book book = bookService.queryBookById(id);
        if(book == null){
            Map<String, Object> resultMap = WebUtils.ToResultMap(new HashMap<>(), "查询不到此图书", 401);
        }
        // 把图书信息转化成为CartItem商品项
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
        // 调用cart.addItem(CartItem);添加商品项
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.addItem(cartItem);

        System.out.println(cart);
        //返回购物车总的商品数量和最后一个添加的商品名称
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("totalCount",cart.getTotalCount());
        dataMap.put("lastAdd",cartItem.getName());
        req.getSession().setAttribute("lastAdd",cartItem.getName());

        Map<String, Object> resultMap = WebUtils.ToResultMap(dataMap, "添加商品成功", 200);
        //将结果集转成json
        Gson gson = new Gson();
        String jsonStr = gson.toJson(resultMap);
        //回传数据给客户端
        resp.getWriter().write(jsonStr);
    }


}
